<?php
namespace My\Model;

use Utuo\UtuoModel;

class ProductGoodsModel extends UtuoModel {
	
	public $priceAttributes = array(
			'0' => '',
			'1' => '日',
			'2' => '周 ',
			'3' => '月',
			'4' => '季',
			'5' => '半年',
			'6' => '年',
			'7' => '无限期',
	);
	
	protected $_auto = array(
		array('create_time', 'time', self::MODEL_INSERT, 'function'),
		array('attribute_values', 'getAttributes', self::MODEL_BOTH, 'callback'),
		array('shipping_cfg', 'getShippingConfig', self::MODEL_BOTH, 'callback'),
		array('efficiency', 'getEfficiency', self::MODEL_BOTH, 'callback'),
		array('brand', 'getBrand', self::MODEL_BOTH, 'callback'),
	);
	
	protected function getShippingConfig() {
		if(!isset($_REQUEST['shipping'])) return false;
		$shippingValues = I("shipping");
		if( empty($shippingValues) )  $shippingValues = array(5, 10, 10);
		return number_format($shippingValues[0], 2).'|'.number_format($shippingValues[1], 2).'|'.number_format($shippingValues[2], 2);
	}
	
	protected function getEfficiency() {
		if(!isset($_REQUEST['efficiency']) or empty($_REQUEST['efficiency'])) return false;
		$shippingValues = I("efficiency");
		return join(",", $shippingValues);
	}
	
	protected function getBrand( $pid ) {
		$pid = $pid ? $pid : session('pid'); // 客户的合作商
		$brandName = $_REQUEST['brand_name'];
		$brandSysId = $_REQUEST['brand_sys'];
		$brand = $_REQUEST['brand'];
		if( empty($_REQUEST['class_id']) or empty($brandName) or !$pid ) return false;
		if ( !empty($brand) ) { // 选择了已有品牌处理
			return $brand;
		} elseif( !empty($brandSysId) ) { // 选择了系统品牌处理
			$partnerBrand = M('PartnerBrand')->where('pid=%d and brand=%d', $pid, $brandSysId)->find();
			if ( !$partnerBrand ) { // 合作商不存在该本牌时添加
				$bid = M('PartnerBrand')->add(array(
						'pid' => $pid,
						'brand' => $brandSysId, ));
				if ( false !== $bid ){
					return $bid;
				}
			}
		} elseif(!empty($brandName)) { // 输入品牌处理
			$partnerBrand = M('PartnerBrand')->where("pid=%d and name='%s'", $pid, $brandName)->find();
			if( $partnerBrand ) {  // 合作商存在同名品牌
				return $partnerBrand['id'];
			} else {
				$bid = M('PartnerBrand')->add(array(
						'pid' => $pid,
						'brand' => 0, 
						'name' => $brandName, ));
				if ( false !== $bid ){
					return $bid;
				}
			}
		}
		return false;
	}
	
	/**
	 * 获得商品属性
	 * @return boolean|string
	 */
	protected function getAttributes() {
		if(!isset($_REQUEST['attribute_values'])) return false;
		$attrString = "";
		$attributeValues = I("attribute_values");
		foreach ($attributeValues as $v) {
			if(isset($v['value']) && isset($v['id'])) {
				$values = array();
				!is_array($v['value']) ? $values[] = $v['value'] : $values = $v['value'];
				foreach ($values as $value) {
					$attrString .= $v['id'].'|'.$value.",";
				}
			}
		}
		empty($attrString) or $attrString = ",".$attrString;
		return $attrString;
	}
	
	/**
	 * 获得产品已设置的规格属性
	 * @param unknown $productGoodsId
	 * @return Ambigous array('产品id'=>array('属性id'=>array('属性值id'=>array('name'=>'', ... ...))))
	 */
	public function getProductStandardAttribute($productGoodsId) {
		$standardSettings = array();
		$attributeStandardLists = M('ProductStandard')->where(array("product_id"=>$productGoodsId))->select();
		foreach ($attributeStandardLists as $v) {
			$standardSettings[$productGoodsId][$v['attribute_id']][$v['attribute_value_id']] = array('name' => $v['name'], 'pic' => $v['pic']);
		}
		return $standardSettings;
	}
	
	
	/**
	 * 获得指定的商品属性与属性值信息
	 * @param unknown $attributeValues 商品已设置的属性与属性值编号
	 * array(
	 * 	  '属性id' => array('属性值id', '属性值id', '属性值id',)
	 * )
	 * @return map
	 */
	public function getAttributesInfo($attributeValues, $productGoodsId) {
		$attributes = array();
		if(!empty($attributeValues)) {
			$attributeValues = is_array($attributeValues) ? $attributeValues : toArray($attributeValues); // 商品已设置的属性与属性值编号
			$productAttributes = M("ProductAttribute")->where(array("id"=>array('in', array_keys($attributeValues))))->getField('id,name,values,multiselect,is_standard'); // 属性详细信息
			$standardSettings = $this->getProductStandardAttribute($productGoodsId); // 获得已设置的规格属性
			foreach($attributeValues as $k => $v) {
				$attr = $productAttributes[$k]; // 该商品某属性原始数据
				/*按已设置的规格属性覆盖*/
				$attributesValues = toArray($attr['values'], 0, 0); // 该商品某属性的所有值(值id不重复)
				foreach ($attributesValues as $valueId => $valueName) {
					$valueCfg = $standardSettings[$productGoodsId][$k][$valueId];
					if($valueCfg) $attributesValues[$valueId] = $valueCfg['name'];
				}
				$currentAttributes = array_intersect_key($attributesValues, array_fill_keys((array)$v, "")); // array(商品当前属性值=>属性名, 商品当前属性值=>属性名, ... ...)
				$attr['values'] = $currentAttributes; // 属性值信息
				$attributes[] = $attr;
			}
		}
		return $attributes;
	}
	
	/**
	 * 获得运费标准
	 * @param unknown $productGoods
	 */
	public function getShippingWay($productGoods) {
		$productGoods and !$productGoods['is_shipping'] and list($s0, $s1, $s2) = explode("|", $productGoods['shipping_cfg']);
		$config = array(
				'1' => array('id' => '1', 'name' => '平邮', 'price' => $s0*1),
				'2' => array('id' => '2', 'name' => '快递', 'price' => $s1*1),
				'3' => array('id' => '3', 'name' => 'EMS', 'price' => $s2*1),
		);
		return $config;
	}
	
	/**
	 * 获得实际运费
	 * @param unknown $id 商品id
	 * @param unknown $quantity 购买数量
	 */
	public function getShipping($id, $quantity) {
		$productGoods = $this->find($id);
		$data = $this->getShippingWay($productGoods);
		foreach ($data as $k => &$v) {
			$v['price'] = $v['price'] * $quantity;
		}
		return $data;
	}
	
	/**
	 * 获得用户将要添加到购物车的商品并转化为购物车可存储的格式
	 * @param int $id 商品id
	 * @param string $attrs 用户选择的商品属性
	 * @return unknown
	 */
	public function getUserSubmitGoods($id, $attrs) {
		$product = $this->find($id);
		if(!$product) { $this->error = '商品已不存在'; return false;}
		// 验证商品属性选择
		$attributeValues = toArray($product['attribute_values']); // 商品属性
		$selectedAttributes = is_array($attrs) ? $attrs : toArray($attrs, 0); // 用户选择的商品属性
		foreach ($attributeValues as $k => $v) {
			$v = (array)$v;
			if(!isset($selectedAttributes[$k])) { $this->error = "属性:{$k}未选择."; return false;}
			if(!in_array($selectedAttributes[$k], $v)) { $this->error = "属性值:{$selectedAttributes[$k]}未找到."; return false;}
		}
		$product['ownerCid'] = $product['cid']; // 商品主
		$product['selectedAttributes'] = $selectedAttributes;
		$product['is_low'] ? $product['productPrice'] = $product['price_low'] : $product['productPrice'] = $product['price'] ;
		return $product;
	}
	
	/**
	 * 更新前处理
	 * @see \Utuo\UtuoModel::_before_update()
	 */
	protected function _before_update(&$data, &$options) {
		// 类目改变时清空属性值
		$productGoods = M("ProductGoods")->find($options["where"]["id"]);
		if(isset($data['class_id']) and $productGoods and $productGoods['class_id'] != $data['class_id']) {
			$data['attribute_values'] = "";
		}
		// 处理更新商品属性
		if(isset($_REQUEST['attribute_values'])) {
			$attributeValues = I("attribute_values");
			/* 删除已取消的规格属性 */
			$productGoodsId = I('id', 0, 'intval');
			$attributeValueIds = $this->getFieldAttributeValues($attributeValues, 'value');
			$condition['_complex'] = array(
									'attribute_id' => array('not in', $this->getFieldValues($attributeValues, 'id')),
									'attribute_value_id' => array('not in', empty($attributeValueIds)? array(0) : $attributeValueIds),
									'_logic' => 'or' );
			$condition['product_id']  = $productGoodsId;
			M('ProductStandard')->where($condition)->delete();
			/* 更新属性 */
			foreach ($attributeValues as $v) {
				if( $v['is_standard'] ) { // 添加与更新规格属性
					if(isset($v['id']) && isset($v['value']) && isset($v['name'])) {
						foreach($v['value'] as $k0 => $v0) {
							$condition = array('cid'=>$productGoods['cid'] ,'product_id'=>$productGoods['id'], 'attribute_id'=>$v['id'], 'attribute_value_id'=>$v0);
							if(M('ProductStandard')->where($condition)->find()) {
								M('ProductStandard')->where($condition)->save(array('name'=> $v['name'][$k0]));
							}else{
								$condition['name'] = $v['name'][$k0];
								M('ProductStandard')->add($condition);
							}
						}
					}
				} else { // 更新常规属性
					
				}
			}
		}
		parent::_before_update($data, $options);
	}
	
	
	/**
	 * 获得列数据
	 * @param unknown $arr
	 * @param unknown $fieldName
	 * @return multitype:unknown
	 */
	private function getFieldValues($arr, $fieldName) {
		$result = array();
		foreach ($arr as $v) $result[] = $v[$fieldName];
		return $result;
	}
	
	/**
	 * 合并所有不同属性数组值
	 * @param unknown $arr
	 * @param unknown $fieldName
	 * @return multitype:unknown
	 */
	private function getFieldAttributeValues($arr, $fieldName) {
		$result = array();
		foreach ($arr as $v) $v[$fieldName] and is_array($v[$fieldName]) and $result = array_merge($result, $v[$fieldName]);
		return $result;
	}
	
}